//
//  UrlRequestManager.m
//  Project_ZFR_MUSIC
//
//  Created by 张福润 on 16/2/29.
//  Copyright © 2016年 张福润. All rights reserved.
//

#import "UrlRequestManager.h"
#define GETURL @"http://api2.pianke.me/read/columns"
#define POSTURL @"http://api2.pianke.me/ting/radio"
static UrlRequestManager *_instance=nil;
@implementation UrlRequestManager
+(void)requestWith:(requestUrlType)Type URL:(NSString *)URL condition:(NSDictionary *)condition SuccessBlock:(successBlock)successBlock faile:(faileBlock)faileBlock{
    if(Type==GET){

        UrlRequestManager *manger=[[UrlRequestManager alloc]init];
        [manger get:URL condition:condition successBlock:successBlock faileBlock:faileBlock];
    }
    else{
        UrlRequestManager *manger=[[UrlRequestManager alloc]init];
        [manger post:URL condition:condition successBlock:successBlock faileBlock:faileBlock];
        
    }
}

-(void)get:(NSString *)getUrl condition:(NSDictionary *)condition successBlock:(successBlock)success faileBlock:(faileBlock)faile{
    NSURLSession *session=[NSURLSession sharedSession];

    
    //拼接URL
   __block NSMutableString *urlStr=[NSMutableString stringWithString:getUrl];
    //拼接
    [urlStr appendString:@"?"];
    
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [urlStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
        });
        
    }];
    //截取
    [urlStr substringToIndex:urlStr.length-2];
    //转码
    //字符串装utf-8
    NSCharacterSet *set=[NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString *urlString=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
//    NSLog(@"%@",urlString);
    //设置request
    NSMutableURLRequest *requset=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //设置请求方式
    [requset setHTTPMethod:@"GET"];
    NSURLSessionTask *task=[session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(data &&!error){
            id item=[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            if(success){
                success(item);
            }
        }
        if(faile){
            faile(error);
        }
        
    }];
    
    [task resume];
}

-(void)post:(NSString *)postUrl condition:(NSDictionary *)condition successBlock:(successBlock)success faileBlock:(faileBlock)faile{
    NSURLSession *session = [NSURLSession sharedSession];
    // 拼接url
    NSMutableString *urlStr = [NSMutableString stringWithString:postUrl];
    // 拼接?
    [urlStr appendString:@"?"];
    
    // 转码
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    // body
    __block NSMutableString *bodyStr = [NSMutableString string];
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [bodyStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
    }];
    [bodyStr substringToIndex:[bodyStr length]-2];
    
    // 设置request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    // 设置body
    NSData *date = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:date];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"data = %@, err = %@",data,error);
        if (data && !error) {
            id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            if (success) {  //如果解析成功
                success(item);
                return ;
            }else {
                NSLog(@"successblock 为空");
                return;
            }
        }
        //
        if (faile) {
            faile(error);
        }
    }];
    [task resume];

}


+(instancetype)shareUrlRequsetManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance=[[UrlRequestManager alloc]init];
    });
    return _instance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance=[super allocWithZone:zone];
    });
    return _instance;
}
@end
